import { PackageInfo } from "@/modules/my-module";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { atom } from "jotai";
import { atomWithStorage, createJSONStorage } from "jotai/utils";

export const appsAtom = atom<PackageInfo[]>([]);
export const showSysAppAtom = atom(false);
export const filterByNameAtom = atom("");
export const filteredAppsAtom = atom<PackageInfo[]>((get) => {
  const apps = get(appsAtom);
  const filter = get(filterByNameAtom).toLowerCase();
  const showSysApp = get(showSysAppAtom);
  let filterAppByName =
    filter.length == 0
      ? apps
      : apps.filter(
          (app) =>
            app.name.toLowerCase().includes(filter) ||
            app.packageName.includes(filter)
        );
  let filterAppBySysApp = showSysApp
    ? filterAppByName
    : filterAppByName.filter((app) => !app.isSystemApp);
  return filterAppBySysApp;
});

export enum PickFunVersion {
  china = "china",
  oversea = "oversea",
}

export enum PickFunDeviceModel {
  p0 = "P0",
  p1 = "P1",
  p3 = "P3", //litter box
  a3 = "A3", 
}

type WifiSetting = {
  ssid: string;
  password: string;
  type: "wpa" | "wep";
  hide: boolean;
};

type qrCodeSetting = {
  version: PickFunVersion;
  sn: string;
};

export type DevSpec = {
  ver: PickFunVersion;
  model: PickFunDeviceModel;
  sn: string | null;
};

const wifiSettingStorage = createJSONStorage<WifiSetting>(() => AsyncStorage);

const qrCodeSettingStorage = createJSONStorage<qrCodeSetting>(
  () => AsyncStorage
);

const continuouslyScanStorage = createJSONStorage<boolean>(() => AsyncStorage);

const soundAlertStorage = createJSONStorage<boolean>(() => AsyncStorage);

export const wifiSettingAtom = atomWithStorage<WifiSetting>(
  "wifiSetting",
  { ssid: "", password: "", type: "wpa", hide: false },
  wifiSettingStorage
);

export const qrCodeSettingAtom = atomWithStorage<qrCodeSetting>(
  "qrCodeSetting",
  { version: PickFunVersion.oversea, sn: "" },
  qrCodeSettingStorage
);

export const continuouslyScanAtom = atomWithStorage(
  "continuouslyScan",
  false,
  continuouslyScanStorage
);

export const soundAlertAtom = atomWithStorage(
  "soundAlert",
  false,
  soundAlertStorage
);

export const scannedDevSpecAtom = atom<DevSpec | null>(null);
